/**
 * 
 */
package com.manthano.util.file;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * @author DELL
 */
public class XLSXFileWriter implements FileWriter
{
	private XSSFWorkbook	workbook			= null;
	private XSSFSheet		writableWorkSheet	= null;
	private int				rowIndex			= 0;
	private OutputStream	outputStream		= null;

	/**
	 * @param outputStream
	 * @throws IOException
	 */
	public XLSXFileWriter(OutputStream outputStream) throws IOException
	{
		this.outputStream = outputStream;
		workbook = new XSSFWorkbook();
		writableWorkSheet = workbook.createSheet("DataSheet");
	}

	public void close() throws IOException
	{
		if (workbook != null)
		{
			workbook = null;
		}
	}

	public void writeNext(Object[] rowData) throws IOException
	{
		XSSFRow row = writableWorkSheet.createRow(rowIndex);
		for (int index = 0; index < rowData.length; index++)
		{
			XSSFCell cell = row.createCell(index);
			if (rowData[index] instanceof String)
			{
				cell.setCellValue(rowData[index].toString());
			}
			else if (rowData[index] instanceof Number)
			{
				cell.setCellValue(Double.parseDouble(rowData[index].toString()));
			}
			else if (rowData[index] instanceof Date)
			{
				cell.setCellValue((Date) rowData[index]);
			}
		}
		workbook.write(outputStream);
		rowIndex++;
	}

	public void writeAll(List<Object[]> allRowsData) throws IOException
	{
		Object[] rowData;
		for (Iterator<Object[]> iterator = allRowsData.iterator(); iterator.hasNext();)
		{
			rowData = iterator.next();
			writeNext(rowData);
		}
	}
}
